#!/bin/bash

uri_ands_iso="http://webdav.data.aad.gov.au/metadata/iso-ands"
aad_uri="http://webdav.data.aad.gov.au"

trapFunction () {
  echo Exiting
}

mkdir -p ~/workspace/XML/ShellScripts/ForAAD
mkdir -p ~/workspace/XML/ShellScripts/ForAAD/WebContent
mkdir -p ~/workspace/XML/ShellScripts/ForAAD/RifCs
rm AAD_link_list.out

read -p "Do you want to retrieve webcontent from AAD before transforming -'Y' for yes ('N' will transform only)?  " choice
echo    # (optional) move to a new line
if [[ $choice =~ ^[Yy]$ ]]
then
  echo Retrieving webcontent from AAD
  
  wget --quiet -O - $uri_ands_iso | grep -oPi '(?<=href=")[^"]*(?=")' >> AAD_link_list.out

  while read link; do

    if [ ${link: -4} == ".xml" ]
    then 

      if [ ${link} != "AAD_RIFCS_ISO.xml" ]
      then

        uri=$aad_uri$link
        echo $uri 

        link_no_extension="${link##*/}"
        echo "Link no extension: "$link_no_extension

        wget --header='Accept-Language: en-us' $uri -O ForAAD/WebContent/${link_no_extension}_wget.xml
      fi
    fi
  done < AAD_link_list.out
fi

rm ~/workspace/XML/ShellScripts/ForAAD/RifCs/*
rm ~/workspace/XML/ShellScripts/ForAAD/RifCs/AADRegistryObjects.xml

echo '<registryObjects xmlns:xs="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns="http://ands.org.au/standards/rif-cs/registryObjects"
                 xsi:schemaLocation="http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/schema/registryObjects.xsd">' >> ~/workspace/XML/ShellScripts/ForAAD/RifCs/AADRegistryObjects.xml


trap trapFunction EXIT
trap 'exit 127' INT

ls ~/workspace/XML/ShellScripts/ForAAD/WebContent | while read f; do
    fileNamePath="~/workspace/XML/ShellScripts/ForAAD/WebContent/""$f"
    fileNameNoExtension=${f%.*}
    echo File: $fileNamePath
    echo Transforming $fileNamePath
    echo java -jar ~/workspace/XML/XSLT/saxon9he.jar ~/workspace/XML/ShellScripts/ForAAD/WebContent/"$f" ~/workspace/XML/XSLT/ISO19139_To_RIFCS/AAD/AAD_ISO19139_rif.xsl > ~/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    java -jar ~/workspace/XML/XSLT/saxon9he.jar \
        ~/workspace/XML/ShellScripts/ForAAD/WebContent/"$f" \
        ~/workspace/XML/XSLT/ISO19139_To_RIFCS/AAD/AAD_ISO19139_rif.xsl \
        > ~/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    echo XML written to ~/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml"

    cat ~/workspace/XML/ShellScripts/ForAAD/RifCs/$fileNameNoExtension"_rif-cs.xml" >> ~/workspace/XML/ShellScripts/ForAAD/RifCs/AADRegistryObjects.xml
   
done

 echo '</registryObjects>' >> ~/workspace/XML/ShellScripts/ForAAD/RifCs/AADRegistryObjects.xml









